#pragma once

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


namespace XMLife
{
	template <class T,class Container = vector<T>,class Compare = less<T>>
	class priorty_queue
	{
	public:

		priorty_queue() = default;

		template <class InputIterator>
		priorty_queue(InputIterator first, InputIterator last)
			:_con(first, last)
		{
			for (int i = (_con.size() - 2) / 2; i >= 0; i--)
			{
				adjust_down(i);
			}
		}
		
		
		void adjust_up(size_t child)
		{
			size_t parent = (child - 1) / 2;
			Compare com;
			while (child > 0)
			{
				//if (_con[parent] < _con[child])
				if(com(_con[parent] , _con[child]))
				{
					swap(_con[parent], _con[child]);
				}
				else
				{
					break;
				}
				child = parent;
				parent = (child - 1) / 2;
			}
		}

		void adjust_down(size_t parent)
		{
			size_t child = parent * 2 + 1;
			Compare com;
			while (child < _con.size())
			{
				if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
				{
					++child;
				}
				//if (_con[parent] < _con[child])
				if (com(_con[parent], _con[child]))
				{
					swap(_con[parent], _con[child]);
				}
				else
				{
					break;
				}
				parent = child;
				child = parent * 2 + 1;
			}
		}

		
		void push(const T& val)
		{
			_con.push_back(val);
			adjust_up(_con.size() - 1);
		}

		const T& top() const
		{
			return _con[0];
		}

		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}

		size_t size()
		{
			return _con.size();
		}

		bool empty()
		{
			return _con.empty();
		}
		
	private:
		Container _con;
	};
}


void Testpriorty_queue()
{
	XMLife::priorty_queue<int,vector<int>> q;
	q.push(1);
	q.push(5);
	q.push(4);
	q.push(2);
	q.push(9);
	
	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}
	cout << endl;
}